// Copyright 2011, Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.google.api.ads.common.lib.auth;

import com.google.api.ads.common.lib.exception.OAuthException;
import com.google.api.client.auth.oauth.OAuthParameters;
import com.google.api.client.http.GenericUrl;
import com.google.inject.Inject;
import com.google.inject.name.Named;

import java.security.GeneralSecurityException;

/**
 * OAuth authorization header provider.
 *
 * @author Adam Rogal
 */
public class OAuthAuthorizationHeaderProvider {

  private final String requestMethod;

  /**
   * Constructor.
   *
   * @param requestMethod the request method that will be authenticated against
   */
  @Inject
  public OAuthAuthorizationHeaderProvider(@Named("requestMethod") String requestMethod) {
    this.requestMethod = requestMethod;
  }

  /**
   * Gets the OAuth authorization header for the parameters and request URL.
   *
   * @param oAuthCompatible exposes the OAuth parameters
   * @param requestUrl the request URL
   * @return the {@code Authorization} header value to set
   * @throws OAuthException if the OAuth header could not be created
   */
  public String getOAuthAuthorizationHeader(OAuthCompatible oAuthCompatible, GenericUrl requestUrl)
      throws OAuthException {
    try {
      OAuthParameters oAuthParameters = oAuthCompatible.getOAuthParameters();
      oAuthParameters.computeNonce();
      oAuthParameters.computeTimestamp();
      oAuthParameters.computeSignature(requestMethod, requestUrl);
      return oAuthParameters.getAuthorizationHeader();
    } catch (GeneralSecurityException e) {
      throw new OAuthException("Unexpected exception occurred.", e);
    }
  }
}
